package com.shiliuzi.www.service.impl;
import com.aliyuncs.exceptions.ClientException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shiliuzi.www.pojo.bo.LimitBo;
import com.shiliuzi.www.pojo.bo.RecordBo;
import com.shiliuzi.www.pojo.bo.RecordTypeBo;
import com.shiliuzi.www.pojo.bo.UserInfoBo;
import com.shiliuzi.www.pojo.dto.revoke.*;
import com.shiliuzi.www.pojo.po.Cancel;
import com.shiliuzi.www.pojo.po.Record;
import com.shiliuzi.www.pojo.po.RecordType;
import com.shiliuzi.www.pojo.vo.revoke.*;
import com.shiliuzi.www.service.RevokeService;
import com.shiliuzi.www.common.Code;
import com.shiliuzi.www.common.Result;
import com.shiliuzi.www.mapper.RevokeMapper;
import com.shiliuzi.www.util.aliyunUtil.StoreAliyunUtil;
import com.shiliuzi.www.util.CommonUtil;
import com.shiliuzi.www.util.LimitUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import static com.shiliuzi.www.common.Code.ERROR;
import static com.shiliuzi.www.common.Code.SUCCESS;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@Slf4j
@Service
public class RevokeServiceImpl implements RevokeService {
    @Resource
    private RevokeMapper revokeMapper;

    @Resource
    private CommonUtil commonUtil;

    @Resource
    private LimitUtil limitUtil;

    @Resource
    private StoreAliyunUtil storeAliyunUtil;


    @Override
    public Result selRecord(RevokeShowDto revokeShowDto) {
//        Record record = revokeShowDto.getRecord();
//        System.out.println(record);
//        RecordType type = record.getType();
//        Integer identity = revokeShowDto.getIdentity();
//        List<Record> records = revokeMapper.selRecord(record, type, identity);
        List<Record> records = revokeMapper.selRecord(null, null, null);
        if (records.size() == 0) {
            return Result.error(ERROR, "查找不到资料");
        }
//        Integer page = revokeShowDto.getPage();
//        Integer pageSize = revokeShowDto.getPageSize();
//        PageHelper.startPage(page, pageSize);
//        Page<Record> p = (Page<Record>) records;//直接调用
//        long total = p.getTotal();
//        Integer totalSize = calculatePage(total, pageSize);
//        RevokeSelectResultDto revokeSelectResultDto = new RevokeSelectResultDto(records, page, pageSize, total, totalSize);
//        return Result.success(SUCCESS, revokeSelectResultDto);
        return Result.success(SUCCESS, records);
    }


    @Override
    public Result setRevoke(RevokeSetDto revokeSetDto, MultipartFile file) throws IOException, ClientException {
        String url = storeAliyunUtil.storeUtil(file);
        revokeSetDto.setPathFile(url);
        int ins = revokeMapper.insRevoke(revokeSetDto);
        if (ins < 1) {

            log.info("添加失败");
            return Result.error(10000, "添加失败");
        }
        log.info("成功插入" + ins + "行");
        return Result.success(Code.SUCCESS, "success");
    }



//    private String storeFile(MultipartFile file) throws IOException {
//        String originalFilename = file.getOriginalFilename();
//        int i = originalFilename.lastIndexOf(".");
//        String newFileName = UUID.randomUUID().toString() + originalFilename.substring(i);
//        file.transferTo(new File("C:/file/" + newFileName));
//        return newFileName;
//    }

    @Override
    public Result updateRevoke(RevokeSetDto revokeSetDto) {
        System.out.println("hi");
        Integer upd = revokeMapper.updRevoke(revokeSetDto);
        log.info("成功修改" + upd + "行");//判断
        return Result.success(Code.SUCCESS, "success");
    }

    @Override
    public Result delRevoke(List<Integer> idList) {
        System.out.println("hi");
        int del = revokeMapper.delRevoke(idList);
        if (del == 0) {
            return Result.error(ERROR, "没有删除到任何信息");//中文
        }
        log.info("删除了" + del + "行");//判断
        return Result.success(SUCCESS, "添加成功");
    }

    @Override
    public Result cancelRecord(Cancel cancel) {
        int i = revokeMapper.insCancelRecord(cancel);
        if(i<1)return Result.error(ERROR,"添加失败");
        return Result.success(SUCCESS,"添加成功");
    }


    /**
     * 计算总页数方法
     * @param total
     * @param pageSize
     * @return
     */
    private Integer calculatePage(long total, Integer pageSize) {
        int allSize;
        if (total % pageSize != 0) {
            allSize = (int) total / pageSize + 1;
        } else allSize = (int) total / pageSize;
        return allSize;
    }

    @Override
    public Result obtainCancelRecord(CancelRecordGetDto cancelRecordGetDto) {

        //1、获取总页数
        Integer pageMax = commonUtil.limitCalculate(
                revokeMapper.obtainRecordPage(cancelRecordGetDto)
                , cancelRecordGetDto.getPageSize()
                , true);
        LimitBo limitBo = limitUtil.limitAdapter(cancelRecordGetDto,pageMax);

        //2、根据传入参数进行获取源数据
        List<Record> records = revokeMapper.obtainCancelRecord(limitBo);

        //3、将数据转为需要类型，即po转为bo
        List<RecordBo> recordBos = commonUtil.copyPropertiesList(records, RecordBo.class);
        if(recordBos == null) return Result.success(Code.SUCCESS
                ,new CancelRecordGetVo(1,0,"暂时没有撤销记录！"));

        //4、返回Result
        return Result.success(Code.SUCCESS
                ,new CancelRecordGetVo(pageMax
                        , limitBo.getVersion()
                        , recordBos));
    }

    @Override
    public Result infoCancelRecord(InfoRecordDto infoRecordDto) {

        infoRecordDto.setUserId(UserInfoBo.obtainUser().getId());
        Integer returnResult = revokeMapper.infoCancelRecord(infoRecordDto);

        if (returnResult.equals(1))
            return Result.success(Code.SUCCESS,new InfoRecordVo("申诉成功！请耐心等候管理员审批！"));

        return Result.success(Code.SUCCESS,new InfoRecordVo("该记录已申述！请耐心等候管理员审批！"));
    }

    @Override
    public Result obtainRecordClass(RecordClassGetDto recordClassGetDto) {

        Integer pageMax = commonUtil.limitCalculate(
                revokeMapper.obtainRecordClassPage(recordClassGetDto),
                recordClassGetDto.getPageSize(),
                true);

        LimitBo limitBo = limitUtil.limitAdapter(recordClassGetDto, pageMax);
        List<RecordType> recordTypes = revokeMapper.obtainRecordClass(limitBo);
        List<RecordTypeBo> recordTypeBos = commonUtil.copyPropertiesList(recordTypes, RecordTypeBo.class);

        if(recordTypeBos == null) Result.success(Code.SUCCESS,
                new RecordClassGetVo<>(1,0,"暂时没有该类别的奖惩类型！"));

        return Result.success(Code.SUCCESS
                ,new RecordClassGetVo<>(
                        pageMax,
                        limitBo.getVersion(),
                        recordTypeBos
                ));
    }

    @Override
    public Result setRecordClass(RecordClassSetDto recordClassSetDto) {

        List<RecordClassSetDto.SingleSetDto> singleSetDtos = recordClassSetDto.getSingleSetDtos();
        Iterator<RecordClassSetDto.SingleSetDto> checkIterator = singleSetDtos.iterator();
        while(checkIterator.hasNext()) {
            RecordClassSetDto.SingleSetDto next = checkIterator.next();
            if (next.getTypes() == null
                    || (!next.getTypes().equals(0)
                    && !next.getTypes().equals(1))) checkIterator.remove();
            if (next.getContents().equals("")) checkIterator.remove();
        }

        if(singleSetDtos.size() == 0) return Result.error(Code.BUE_PARAM_ERR, "用户传入参数有误！请重新检查！");

        Integer successNum = revokeMapper.setRecordClass(recordClassSetDto);

        if (singleSetDtos.size() != successNum)
            return Result.success(Code.SUCCESS
                    ,new RecordClassSetVo(successNum,"部分类型已存在！"));

        return Result.success(Code.SUCCESS
                ,new RecordClassSetVo(successNum,"添加类型成功！"));
    }

    @Override
    public Result updateRecordClass(RecordClassUpdateDto recordClassUpdateDto) {

        Integer returnResult = revokeMapper.updateRecordClass(recordClassUpdateDto);

        if(recordClassUpdateDto.equals(0)) return Result.success(
                Code.SUCCESS,
                new RecordClassUpdateVo(
                        returnResult,
                        "该类型无法载入类型库中！"));

        return Result.success(
                Code.SUCCESS,
                new RecordClassUpdateVo(
                        returnResult,
                        "该类型载入类型库成功！"));
    }

    @Override
    public Result banOrRecoverRevokeClass(RecordClassBanDto recordClassBanDto) {

        if (recordClassBanDto.getChoose().equals(0) || recordClassBanDto.getChoose().equals(1))
            return Result.success(Code.SUCCESS,"成功修改！请注意查看！");

        return Result.error(Code.BUE_PARAM_ERR, "该类型无法进行修改！请查看传入数据是否正确！");
    }

    @Override
    //TODO 加锁
    public Result updateDelRecordClass(RecordClassDelDto recordClassDelDto) {

        if (revokeMapper.deleteRecordClass(recordClassDelDto) == 0) return Result.error(Code.ERROR
                ,"该类型不存在！");

        commonUtil.obtainThread(()->{
            revokeMapper.updateDelRecordClass(recordClassDelDto);
        });

        return Result.success(Code.SUCCESS
                ,new RecordClassDelVo(1,"更新中！请稍后！"));
    }
}
